//
//  EditGroupImgViewController.m
//  SouthChina
//
//  Created by kc on 15/8/17.
//  Copyright (c) 2015年 科创. All rights reserved.
//修改群头像与名称

#import "EditGroupImgViewController.h"
#import "TakePhotoController.h"
#import "ContactDao.h"
#import "MessageSessionDao.h"
#import "GroupInfoViewController.h"

@interface EditGroupImgViewController ()<UITextFieldDelegate>{
   Contact *contact;
    NSString *sOldName; //之前的群名称，只有有更新才调用接口
}
@property (strong, nonatomic) IBOutlet UIButton *btImage;
@property (strong, nonatomic) UIImageView *  headImage;//头像
@property (strong, nonatomic) IBOutlet UITextField *groupName;//群名称
@property (strong, nonatomic) TakePhotoController * takephoto;
@end

@implementation EditGroupImgViewController
@synthesize groupId;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self addTitleBarWithBackBtn:@"修改头像与名称" needReturn:YES];
    
    UIView * viewBody = [[[NSBundle mainBundle] loadNibNamed:@"EditGroupImgViewBody" owner:self options:nil] objectAtIndex:0];
    viewBody.frame = (CGRect){0, self.titlebar.frame.origin.y+self.titlebar.frame.size.height,SCREEN_WIDTH, SCREEN_HEIGHT-self.titlebar.frame.size.height};
    [self.view addSubview:viewBody];
    
    contact = [ContactDao getContactById:groupId];
    sOldName = contact.mNAME;
    
    NSURL *url= [NSURL URLWithString: [contact.mHEAD_IMG hasPrefix:@"http"]?contact.mHEAD_IMG:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,contact.mHEAD_IMG]];
    _headImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 46,46)];
    [_headImage setBackgroundColor:[UIColor clearColor]];
    [_headImage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
    _headImage.layer.masksToBounds = YES;
    _headImage.layer.cornerRadius = 23;
    [_btImage addSubview:_headImage];
    
    _groupName.text = contact.mNAME;
    _groupName.placeholder = @"请填写群名称(2-10个字)";
    _groupName.delegate = self;
   
    
    //标题栏上显示完成按钮
    UIButton *finishBtn = [[UIButton alloc] initWithFrame:CGRectMake(266, self.titlebar.frame.origin.y+20, 50, 40)];
    [finishBtn addTarget:self action:@selector(finishBtn:) forControlEvents:UIControlEventTouchUpInside];
    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
    finishBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [self.titlebar addSubview:finishBtn];
}

//完成事件
-(void)finishBtn:(id)sender{
    NSLog(@"点击完成事件");
    
    if([sOldName isEqualToString:_groupName.text])
    {
        //回退到上一级页面
        [self.navigationController popViewControllerAnimated:YES];
         GroupInfoViewController *GrouupInfowC = [self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count-1)];
        [GrouupInfowC showAlerHUD:@"修改成功！"];
        return;
    }
    //判断是 2-10个字
    if(_groupName.text.length<2 ||  _groupName.text.length>10)
    {
        [self showAlerHUD:@"群名称需要2-10个字符"];
    }
    else{
        [self.view endEditing:YES];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [DE serverCall:@"updateGrpName" params:@{@"groupId":groupId,@"groupName":_groupName.text} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if(success){
                MessageSession *mesSession = [MessageSessionDao queryMsgSessionById:[NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2G,groupId]];
                //更新群名称
                mesSession.title = _groupName.text;
                mesSession.upate_time = [NSDate date];
                [MessageSessionDao updateMessageSession:mesSession];
                
                NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
                NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
                [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                    
                    if(success){
                        @try {
                            [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:mesSession.sess_id businessId:@"updateGrpName" sendout:YES];
                            //回退到上一级页面
                            [self.navigationController popViewControllerAnimated:YES];
                            GroupInfoViewController *GrouupInfowC = [self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count-1)];
                            [GrouupInfowC showAlerHUD:@"修改成功！"];
                        }
                        @catch (NSException *exception) {
                            [self showAlerHUD:@"修改成功:本地更新失败！"];
                        }
                        
                    }else{
                        [self showAlerHUD:@"修改成功：服务器同步失败！"];
                        
                    }
                    
                }];
            }else{
                
                [self showAlerHUD:@"修改失败！"];
            }
        }];
    }
    
}

//重写提示效果(个性化)
-(void)showAlerHUD:(NSString*)text
{
    BDKNotifyHUD * hudex = [[BDKNotifyHUD alloc] initWithImage:[UIImage imageNamed:@""]  text:text];
    hudex.center = CGPointMake(self.view.center.x, _btImage.frame.origin.y+500);
    [self.view addSubview:hudex];
    [hudex presentWithDuration:1.5 speed:0.5f inView:self.view completion:^{
        [hudex removeFromSuperview];
    }];
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField endEditing:YES];
    return YES;
}


//点击头像事件
- (IBAction)btImgClicked:(id)sender
{
    NSLog(@"点击头像事件");
    //普通群组可以修改头像，讨论组不可以修改群头像
    if([contact.mORG_TYPE isEqualToString:@"Group"])
    {
        _takephoto = [TakePhotoController new];
        _takephoto.type = TakePhotoFromPhotoLibrary;
        _takephoto.isEdit = YES;
        __weak EditGroupImgViewController *ctl = self;
        _takephoto.blockComplete = ^(UIImage * image,NSDictionary*fileMap){
            
            [UploadFile uploadFileWithFilePath:[fileMap objectForKey:@"file"] servicePath:@"HEAD_IMG" params:fileMap calback:^(BOOL success, int code, NSString *desc, NSDictionary *netdata, NSDictionary *params) {
                
                if (success) {
                    NSLog(@"图像****URL:::::::%@",[netdata objectForKey:@"URL"]);
                    NSDictionary *params = @{@"groupId":groupId,@"headImg":[netdata objectForKey:@"URL"]};
                    [MBProgressHUD showHUDAddedTo:ctl.view animated:YES];
                    
                    [DE serverCall:@"updateGrpHeadImg" params:params callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
                        [MBProgressHUD hideHUDForView:ctl.view animated:YES];
                        if(success)
                        {
                            [ctl.headImage setImage:image];
                            //更新本地通讯录
                            NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
                            NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
                            [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                                if(success){
                                    [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];}
                            }];
                        }
                    }];
                }
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:success?@"更新头像成功!":@"更新头像失败！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                
            }];
            
        };
        
        [_takephoto startTakePhotoFromViewControl:kAppDelegate.iCSDrawerController];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)btnBack {
    kAppDelegate.needRefrsh = YES;
    [super btnBack];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
